package com.example.shop_front_api.controller;

import com.example.shop_front_api.entity.MemberAddress;
import com.example.shop_front_api.service.MemberAddressService;
import com.example.shop_front_api.utils.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("api/members/address")
public class MemberAddressController {

    @Autowired
    private MemberAddressService memberAddressService;

    // 添加收货地址
    @PostMapping("add")
    public JsonResult addAddress(@RequestBody MemberAddress memberAddress) {
        int result = memberAddressService.addAddress(memberAddress);
        if (result > 0) {
            return JsonResult.success("添加成功", null);
        } else {
            return JsonResult.failed("添加失败");
        }
    }

    //收货列表
    @GetMapping("list")
    public JsonResult getAddressList(@RequestParam("memberId") int memberId) {
        List<MemberAddress> address = memberAddressService.getAddressByMemberId(memberId);
        return JsonResult.success("获取成功", address);
    }

    //收货地址详情
    @GetMapping("detail")
    public JsonResult getAddressDetail(@RequestParam("id") int id) {
        MemberAddress address = memberAddressService.getAddressById(id);
        if (address != null) {
            return JsonResult.success("获取成功", address);
        }else{
            return JsonResult.failed("地址不存在");
        }
    }

    //编辑收货地址
    @PostMapping("update")
    public JsonResult updateAddress(@RequestBody MemberAddress address) {
        int result = memberAddressService.updateAddress(address);
        if (result > 0) {
            return JsonResult.success("更新成功", null);
        }else {
            return JsonResult.failed("更新失败");
        }
    }

    //删除收货地址
    @PostMapping("delete")
    public JsonResult deleteAddress(@RequestParam("id") int id,@RequestParam("memberId") int memberId) {
        int result = memberAddressService.deleteAddress(id,memberId);
        if (result > 0) {
            return JsonResult.success("删除成功", null);
        }else {
            return JsonResult.failed("删除失败");
        }
    }

    //设置默认地址
    @PostMapping("set_defualt")
    public JsonResult setDefualtAddress(@RequestParam("id") int id,@RequestParam("memberId") int memberId) {
        int result = memberAddressService.setDefaultAddress(id,memberId);
        if (result > 0) {
            return JsonResult.success("设置成功", null);
        }else{
            return JsonResult.failed("设置失败");
        }
    }

    //获取默认地址
    @GetMapping("default")
    public JsonResult getDefaultAddress(@RequestParam("memberId") int memberId) {
        MemberAddress address = memberAddressService.getDefaultAddressByMemberId(memberId);
        if (address != null) {
            return JsonResult.success("获取成功", address);
        }else{
            return JsonResult.failed("暂无默认地址");
        }
    }
}